package com.aiyige.page.discovery;


import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventLogout;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.advertisement.model.AdResponse;
import com.aiyige.page.discovery.adapter.ActivityDataAdapter;
import com.aiyige.page.discovery.adapter.DiscoveryAdapter;
import com.aiyige.page.discovery.model.ActivityData;
import com.aiyige.page.discovery.model.ActivityResp;
import com.aiyige.page.webview.util.PreloadUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.banner.Banner;
import com.aiyige.utils.banner.BannerAdapter;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class DiscoveryPage extends BaseFragment implements CommonDataView.RetrofitStub {
    @BindView(R.id.cdv)
    CommonDataView cdv;
    Unbinder unbinder;
    DiscoveryAdapter discoveryAdapter;

    Banner banner;
    View learnVideoLayout;
    View majorCourseLayout;

    RecyclerView bannerIndicatorRv;
    BannerAdapter bannerAdapter;
    Handler mainHandler;
    View haveCouponLayout;
    RecyclerView activityRv;
    ActivityDataAdapter activityDataAdapter;
    int availableCouponCount = 0;

    public DiscoveryPage() {
    }

    public static DiscoveryPage newInstance() {
        DiscoveryPage fragment = new DiscoveryPage();
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainHandler = new Handler(Looper.getMainLooper());
        View view = inflater.inflate(R.layout.page_discovery, container, false);
        unbinder = ButterKnife.bind(this, view);
        discoveryAdapter = new DiscoveryAdapter();
        discoveryAdapter.setHeaderAndEmpty(true);
        cdv.config(discoveryAdapter, this);
        initHeader();
//        requestData();
        return view;
    }

    public void initHeader() {
        View header = LayoutInflater.from(getContext()).inflate(R.layout.discovery_page_header, (ViewGroup) cdv.getRecyclerView().getParent(), false);
        discoveryAdapter.addHeaderView(header);
        banner = (Banner) header.findViewById(R.id.banner);
        learnVideoLayout = header.findViewById(R.id.learnVideoLayout);
        majorCourseLayout = header.findViewById(R.id.majorCourseLayout);
        haveCouponLayout = header.findViewById(R.id.haveCouponLayout);
        haveCouponLayout.setVisibility(View.GONE);
        haveCouponLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.DrawCouponPage)
                        .navigation(getActivity());
            }
        });
        activityRv = header.findViewById(R.id.activityRv);
        bannerIndicatorRv = (RecyclerView) header.findViewById(R.id.bannerIndicatorRv);
        learnVideoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.LearnFilterPage)
                        .withString("subject", Moment.SUBJECT_VIDEO_COURSE)
                        .navigation();
            }
        });

        majorCourseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.LearnFilterPage)
                        .withString("subject", Moment.SUBJECT_MAJOR_COURSE)
                        .navigation();
            }
        });
        bannerAdapter = new BannerAdapter(getChildFragmentManager());
        bannerAdapter.setupWithBanner(banner);
        bannerAdapter.setupWithIndicator(bannerIndicatorRv);
        cdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                requestData();
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        cdv.setErrorHandler(new CommonDataView.ErrorHandler() {
            @Override
            public void onResponseError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }

            @Override
            public void onNetError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }
        });
        activityRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index == 0) {
                    outRect.set(UIHelper.dip2px(15), UIHelper.dip2px(15), UIHelper.dip2px(7.5f), UIHelper.dip2px(15));
                } else if (index == 1) {
                    outRect.set(UIHelper.dip2px(7.5f), UIHelper.dip2px(15), UIHelper.dip2px(15f), UIHelper.dip2px(15));
                } else if (index % 2 == 0) {
                    outRect.set(UIHelper.dip2px(15), 0, UIHelper.dip2px(7.5f), UIHelper.dip2px(15));
                } else {
                    outRect.set(UIHelper.dip2px(7.5f), 0, UIHelper.dip2px(15), UIHelper.dip2px(15));
                }
            }
        });
        activityRv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        activityDataAdapter = new ActivityDataAdapter();
        activityDataAdapter.bindToRecyclerView(activityRv);
        activityDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ActivityData activityData = activityDataAdapter.getItem(position);
                ARouter.getInstance().build(ARouterConfig.ActivityFilterPage)
                        .withParcelable("activityData", activityData)
                        .navigation();
            }
        });
    }

    public void requestData() {
        new RequestDataTask(this.getActivity()).execute();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        requestData();
        cdv.doRefreshRequest();
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().guessYouLike(currentPage, 15);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectRegion(EventSelectRegion event) {
        cdv.doRefreshRequest();
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment safeMoment = new Moment(moment);
                resultList.add(safeMoment);
                PreloadUtil.preloadH5Moment(safeMoment);
            }
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                    .build());
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        List<BannerAdapter.Data> bannerAdapterDataList = new LinkedList<>();
        List<ActivityData> activityDataList = new LinkedList<>();

        public RequestDataTask(Activity activity) {
            super(activity);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            bannerAdapter.setData(bannerAdapterDataList);
            activityDataAdapter.setNewData(activityDataList);
            haveCouponLayout.setVisibility(availableCouponCount > 0 ? View.VISIBLE : View.GONE);
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getAd("discover_top").execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<AdResponse> adResponseList = JSON.parseArray(json, AdResponse.class);
                for (AdResponse adResponse : adResponseList) {
                    BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                    bannerAdapterData.setId(adResponse.getId());
                    bannerAdapterData.setUrl(adResponse.getAppAdvertiseUrl());
                    bannerAdapterData.setRouter(adResponse.getLink());
                    bannerAdapterDataList.add(bannerAdapterData);
                }
            } catch (Exception e) {

            }

            try {
                Response<ResponseBody> response = ApiManager.getService().getActivityEntry(ActivityData.extractIdList(activityDataAdapter.getData())).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<ActivityResp> activityRespList = JSON.parseArray(json, ActivityResp.class);
                activityDataList = ActivityData.parse(activityRespList);
            } catch (Exception e) {

            }

            try {
                if (!AccountUtil.isLogin()) {
                    throw new Exception(StringUtils.getString(R.string.please_login));
                }
                Response<ResponseBody> response = ApiManager.getService().getAvailableCouponCount().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                JSONObject jsonObject = JSON.parseObject(json);
                availableCouponCount = jsonObject.getIntValue("count");
            } catch (Exception e) {
                availableCouponCount = 0;
            }
            return null;
        }
    }


    @OnClick({R.id.searchBar, R.id.scanBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.searchBar:
                ARouter.getInstance()
                        .build(ARouterConfig.GlobalSearchPage)
                        .navigation();
                break;
            case R.id.scanBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.ScanQRCodePage)
                        .navigation(getActivity());
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isVisible() && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_FIND
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH) {
            requestData();
            cdv.backToTop(false);
            cdv.showRefreshing();
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    cdv.doRefreshRequest();
                }
            }, 1000);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogin event) {
        if (AccountUtil.isLogin()) {
            initData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogout event) {
        if (!AccountUtil.isLogin()) {
            haveCouponLayout.setVisibility(View.GONE);
        }
    }

}
